package com.lwh.util;



import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;

/**
 * @Description:
 * @Date: 2019-10-15
 * @author: luowuhui
 */
@Slf4j
public class ThreadPoolUtils {
	/**
	 * 向线程池中添加任务方法
	 */
	public static <T> List<T> addExecuteTaskResult (ThreadPoolExecutor threadPoolExecutor,Collection<Callable<T>> tasks) {
		Queue<Future<T>> queue = addExecuteTask(threadPoolExecutor,tasks);
		if (queue != null) {
			List<T>   resultList = new ArrayList<>();
			Future<T> future;
			while ((future = queue.peek()) != null) {
				try {
					if (future.isDone()) {
						resultList.add(future.get());
						queue.poll();
					} else {
						Thread.sleep(50);
						log.debug("deal async task not Done");
					}
				} catch (InterruptedException e) {
					log.error("",e);
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 向线程池中添加任务方法
	 */
	public static <T> Queue<Future<T>> addExecuteTask (ThreadPoolExecutor threadPoolExecutor,Collection<Callable<T>> tasks) {
		log.info("批量提交任务到线程池....");
		if (tasks != null || !tasks.isEmpty()) {
			Queue<Future<T>> queue = new ArrayBlockingQueue<>(tasks.size());
			for (Callable<T> task : tasks) {
				Future<T> submit = threadPoolExecutor.submit(task);
				queue.add(submit);
			}
			return queue;
		}
		return null;
	}

	/**
	 * 向线程池中添加任务方法
	 */
	public static <T> Future<T> addExecuteTaskFuture (ThreadPoolExecutor threadPoolExecutor,Callable<T> task) {
		if (task != null) {
			Future<T> submit = threadPoolExecutor.submit(task);
			return submit;
		}
		return null;
	}

	/**
	 * 向线程池中添加任务方法
	 */
	public static <T> T addExecuteTaskResult (ThreadPoolExecutor threadPoolExecutor,Callable<T> task) {
		return getTaskResult(addExecuteTaskFuture(threadPoolExecutor,task));
	}

	/**
	 * 获取任务结果
	 * @param tFuture 任务
	 * @param <T>
	 * @return
	 */
	public static <T> T getTaskResult (Future<T> tFuture) {
		while (true) {
			try {
				if (tFuture.isDone()) {
					T t = tFuture.get();
					return t;
				} else {
					Thread.sleep(50);
					log.debug("deal async task not Done");
				}
			} catch (InterruptedException | ExecutionException e) {
				log.error("",e);
				return null;
			}
		}
	}

	/**
	 * 向线程池中添加任务方法
	 */
	public static void addExecuteTask (ThreadPoolExecutor threadPoolExecutor,Runnable task) {
		if (task != null) {
			threadPoolExecutor.execute(task);
		}
	}

}
